import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'url';

// 在 ESM 中获取 __dirname
const __dirname = path.dirname(fileURLToPath(import.meta.url));
let savedConfig;

/**
 * 为运行时框架准备打包产物的插件
 * @param {Object} options 
 * @param {String} options.pageName 
 * @returns {undefined | Promise<void>}
 */
function tffConfig() {
  return {
    name: 'tff-config',
    configResolved(resolvedConfig) {
      // 保存解析后的配置以便稍后使用
      savedConfig = resolvedConfig;
    },
    closeBundle(err) {
      if (err) {
        console.error(err);
        return;
      }
      //let appCode = savedConfig.env.VITE_APP_CODE

      console.log('\n');
      console.log(`----删除index.html 文件----`);
     

      fs.rmSync(path.resolve(__dirname, `../dist/index.html`), { force: true });
      fs.rmSync(path.resolve(__dirname, `../dist/favicon.ico`), { force: true });
      // 复制dependencies
      console.log(`----复制 tff.runtime.config.ejs 文件----`);
      const srcPath = path.resolve(__dirname, `../tff.runtime.config.ejs`);
      const targetPath = path.resolve(__dirname, `../dist/tff.runtime.config.ejs`);
      fs.copyFileSync(`${srcPath}`, `${targetPath}`);

      try {
        // 复制依赖
        console.log(`----复制 dependencies 文件----`);
        const dependenciesSrc = path.resolve(__dirname, `../dependencies.js`);
        const dependenciesTarget = path.resolve(__dirname, `../dist/dependencies.js`);
        fs.copyFileSync(`${dependenciesSrc}`, `${dependenciesTarget}`);

      }catch(e){
        //donothing
      }

    }
  };
}

export default tffConfig;